<?php

namespace App\Http\Controllers;

use App\Cate;
use App\Video;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use vod\Request\V20170321 as vod;

class IndexController extends Controller
{

    /**
     * 首页
     */
    public function index()
    {
        $cate_list = Cate::all();
        foreach($cate_list as $one_cate){
            $video_list[] = Video::where('cate','=',$one_cate->cate_id)->orderBy('id','desc')->limit(3)->get()->toArray();
        }
        return view('welcome',['video_list'=>$video_list]);
    }

    public function video_detail($video_id){
        $video_info = Video::find($video_id);
        $cate_info = Cate::where('cate_id',$video_info->cate)->first();
        $play_auth = $this->testGetVideoPlayAuth($video_info->path);
        if(Auth::check()){
            $video_id_list = Auth::user()->video_id;
            $video_id_list = explode(',',$video_id_list);
            if(in_array($video_id,$video_id_list)){
                $has_auth = 1;
            }
        }
        if(!isset($has_auth)){
            $has_auth = 0;
        }

        return view('video_detail',[
            'video_info'=>$video_info,
            'play_auth'=>$play_auth,
            'cate_info'=>$cate_info,
            'has_auth'=>$has_auth,
        ]);
    }

    function testGetVideoPlayAuth($videoId) {
        $regionId = 'cn-shanghai';  // 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
        $profile = \DefaultProfile::getProfile($regionId, env('accessKeyId'), env('accessKeySecret'));
        $client =  new \DefaultAcsClient($profile);
        $request = new vod\GetVideoPlayAuthRequest();
        $request->setAcceptFormat('JSON');
        $request->setRegionId('cn-shanghai');
        $request->setVideoId($videoId);            //视频ID
        $response = $client->getAcsResponse($request);
        return $response;
    }

    public function video_list($cate_id){
        $video_list = Video::where('cate',$cate_id)
            ->orderBy('id','desc')
            ->paginate(9);
        $cate_info = Cate::where('cate_id',$cate_id)->first();
        return view('video_list',['video_list'=>$video_list,'cate_info'=>$cate_info]);
    }

}
